<template>
  <view class="payment-container">
    <!-- 订单信息 -->
    <view class="order-section">
      <view class="section-title">订单信息</view>
      
      <view class="expert-info">
        <u-avatar :src="expert.avatar" size="50"></u-avatar>
        <view class="expert-details">
          <text class="expert-name">{{ expert.name }}</text>
          <text class="expert-title">{{ expert.title }} · {{ expert.hospital }}</text>
        </view>
      </view>
      
      <view class="service-info">
        <view class="service-item">
          <text class="service-label">咨询服务</text>
          <text class="service-value">{{ serviceInfo.name }}</text>
        </view>
        <view class="service-item">
          <text class="service-label">服务说明</text>
          <text class="service-value">{{ serviceInfo.description }}</text>
        </view>
        <view class="service-item">
          <text class="service-label">服务费用</text>
          <text class="service-price">¥{{ serviceInfo.price }}</text>
        </view>
      </view>
    </view>
    
    <!-- 优惠券 -->
    <view class="coupon-section" @click="selectCoupon">
      <view class="section-title">优惠券</view>
      <view class="coupon-selector">
        <view class="coupon-info">
          <u-icon name="coupon" size="20" color="#ff4757"></u-icon>
          <text class="coupon-text">
            {{ selectedCoupon ? `已选择：${selectedCoupon.name}` : '选择优惠券' }}
          </text>
        </view>
        <view class="coupon-discount">
          <text v-if="selectedCoupon" class="discount-text">-¥{{ selectedCoupon.discount }}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
    </view>
    
    <!-- 费用明细 -->
    <view class="cost-section">
      <view class="section-title">费用明细</view>
      
      <view class="cost-list">
        <view class="cost-item">
          <text class="cost-label">服务费用</text>
          <text class="cost-value">¥{{ serviceInfo.price }}</text>
        </view>
        
        <view v-if="selectedCoupon" class="cost-item discount">
          <text class="cost-label">优惠券折扣</text>
          <text class="cost-value">-¥{{ selectedCoupon.discount }}</text>
        </view>
        
        <view class="cost-item total">
          <text class="cost-label">实付金额</text>
          <text class="cost-value total-price">¥{{ finalPrice }}</text>
        </view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-method-section">
      <view class="section-title">支付方式</view>
      
      <view class="payment-methods">
        <view 
          v-for="method in paymentMethods" 
          :key="method.id"
          class="payment-method"
          :class="{ active: selectedPaymentMethod === method.id }"
          @click="selectPaymentMethod(method.id)"
        >
          <view class="method-info">
            <u-icon :name="method.icon" size="24" :color="method.color"></u-icon>
            <text class="method-name">{{ method.name }}</text>
          </view>
          
          <view class="method-selector">
            <u-icon 
              :name="selectedPaymentMethod === method.id ? 'checkmark-circle-fill' : 'circle'" 
              size="20" 
              :color="selectedPaymentMethod === method.id ? '#007aff' : '#ddd'"
            ></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 服务协议 -->
    <view class="agreement-section">
      <view class="agreement-checkbox" @click="toggleAgreement">
        <u-icon 
          :name="agreedToTerms ? 'checkbox-mark' : 'checkbox'" 
          size="18" 
          :color="agreedToTerms ? '#007aff' : '#ddd'"
        ></u-icon>
        <text class="agreement-text">
          我已阅读并同意
          <text class="agreement-link" @click.stop="viewAgreement">《咨询服务协议》</text>
        </text>
      </view>
    </view>
    
    <!-- 底部支付按钮 -->
    <view class="bottom-payment">
      <view class="payment-info">
        <text class="payment-label">实付金额</text>
        <text class="payment-amount">¥{{ finalPrice }}</text>
      </view>
      
      <u-button 
        type="primary" 
        class="pay-button"
        :disabled="!agreedToTerms || paying"
        :loading="paying"
        @click="submitPayment"
      >
        {{ paying ? '支付中...' : '立即支付' }}
      </u-button>
    </view>
    
    <!-- 优惠券选择弹窗 -->
    <u-popup 
      v-model="showCouponPopup" 
      mode="bottom" 
      border-radius="20"
      :safe-area-inset-bottom="true"
    >
      <view class="coupon-popup">
        <view class="popup-header">
          <text class="popup-title">选择优惠券</text>
          <u-icon name="close" size="20" color="#999" @click="showCouponPopup = false"></u-icon>
        </view>
        
        <scroll-view class="coupon-list" scroll-y>
          <view 
            v-for="coupon in availableCoupons" 
            :key="coupon.id"
            class="coupon-item"
            :class="{ selected: selectedCoupon?.id === coupon.id }"
            @click="chooseCoupon(coupon)"
          >
            <view class="coupon-content">
              <view class="coupon-amount">
                <text class="coupon-symbol">¥</text>
                <text class="coupon-value">{{ coupon.discount }}</text>
              </view>
              <view class="coupon-details">
                <text class="coupon-name">{{ coupon.name }}</text>
                <text class="coupon-condition">{{ coupon.condition }}</text>
                <text class="coupon-expire">有效期至：{{ formatDate(coupon.expireTime) }}</text>
              </view>
            </view>
            
            <view class="coupon-selector">
              <u-icon 
                :name="selectedCoupon?.id === coupon.id ? 'checkmark-circle-fill' : 'circle'" 
                size="20" 
                :color="selectedCoupon?.id === coupon.id ? '#007aff' : '#ddd'"
              ></u-icon>
            </view>
          </view>
          
          <view v-if="availableCoupons.length === 0" class="no-coupons">
            <text class="no-coupons-text">暂无可用优惠券</text>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <u-button 
            type="primary" 
            class="confirm-button"
            @click="confirmCoupon"
          >
            确认选择
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';

// 专家接口
interface Expert {
  id: string;
  name: string;
  avatar: string;
  title: string;
  hospital: string;
}

// 服务信息接口
interface ServiceInfo {
  type: string;
  name: string;
  description: string;
  price: number;
}

// 优惠券接口
interface Coupon {
  id: string;
  name: string;
  discount: number;
  condition: string;
  expireTime: string;
  minAmount: number;
}

// 支付方式接口
interface PaymentMethod {
  id: string;
  name: string;
  icon: string;
  color: string;
}

// 订单接口
interface Order {
  id: string;
  expertId: string;
  serviceType: string;
  originalPrice: number;
  discountAmount: number;
  finalPrice: number;
  paymentMethod: string;
  couponId?: string;
}

@Component
export default class PaymentPage extends Vue {
  // 数据属性
  expertId: string = '';
  serviceType: string = '';
  expert: Expert = {} as Expert;
  serviceInfo: ServiceInfo = {} as ServiceInfo;
  
  selectedCoupon: Coupon | null = null;
  selectedPaymentMethod: string = 'wechat';
  agreedToTerms: boolean = false;
  paying: boolean = false;
  
  showCouponPopup: boolean = false;
  availableCoupons: Coupon[] = [];
  
  // 支付方式列表
  paymentMethods: PaymentMethod[] = [
    {
      id: 'wechat',
      name: '微信支付',
      icon: 'weixin',
      color: '#09bb07'
    },
    {
      id: 'alipay',
      name: '支付宝',
      icon: 'zhifubao',
      color: '#1677ff'
    },
    {
      id: 'balance',
      name: '余额支付',
      icon: 'wallet',
      color: '#ff6b35'
    }
  ];
  
  // 计算属性
  get finalPrice(): number {
    const originalPrice = this.serviceInfo.price || 0;
    const discount = this.selectedCoupon?.discount || 0;
    return Math.max(0, originalPrice - discount);
  }
  
  // 生命周期
  onLoad(options: any) {
    this.expertId = options.expertId || '';
    this.serviceType = options.serviceType || 'text';
    
    if (this.expertId && this.serviceType) {
      this.loadExpertInfo();
      this.initServiceInfo();
      this.loadAvailableCoupons();
    }
  }
  
  // 方法
  
  /**
   * 加载专家信息
   */
  async loadExpertInfo() {
    try {
      const response = await get(`/experts/detail/${this.expertId}`);
      this.expert = response.data.expert;
    } catch (error) {
      console.error('加载专家信息失败:', error);
      
      // 使用模拟数据
      this.expert = this.getMockExpert();
    }
  }
  
  /**
   * 初始化服务信息
   */
  initServiceInfo() {
    const serviceMap: Record<string, ServiceInfo> = {
      text: {
        type: 'text',
        name: '图文咨询',
        description: '专家1对1图文解答，24小时内回复',
        price: 50
      },
      voice: {
        type: 'voice',
        name: '语音咨询',
        description: '专家语音通话，实时沟通解答',
        price: 80
      },
      video: {
        type: 'video',
        name: '视频咨询',
        description: '面对面视频通话，更直观的交流',
        price: 100
      }
    };
    
    this.serviceInfo = serviceMap[this.serviceType] || serviceMap.text;
  }
  
  /**
   * 加载可用优惠券
   */
  async loadAvailableCoupons() {
    try {
      const response = await get('/coupons/available', {
        serviceType: this.serviceType,
        amount: this.serviceInfo.price
      });
      this.availableCoupons = response.data.coupons || [];
    } catch (error) {
      console.error('加载优惠券失败:', error);
      
      // 使用模拟数据
      this.availableCoupons = this.getMockCoupons();
    }
  }
  
  /**
   * 选择优惠券
   */
  selectCoupon() {
    this.showCouponPopup = true;
  }
  
  /**
   * 选择优惠券
   */
  chooseCoupon(coupon: Coupon) {
    // 检查是否满足使用条件
    if (this.serviceInfo.price < coupon.minAmount) {
      uni.showToast({
        title: `订单金额需满${coupon.minAmount}元`,
        icon: 'none'
      });
      return;
    }
    
    this.selectedCoupon = coupon;
  }
  
  /**
   * 确认优惠券选择
   */
  confirmCoupon() {
    this.showCouponPopup = false;
  }
  
  /**
   * 选择支付方式
   */
  selectPaymentMethod(methodId: string) {
    this.selectedPaymentMethod = methodId;
  }
  
  /**
   * 切换协议同意状态
   */
  toggleAgreement() {
    this.agreedToTerms = !this.agreedToTerms;
  }
  
  /**
   * 查看服务协议
   */
  viewAgreement() {
    uni.navigateTo({
      url: '/pages/agreement/service'
    });
  }
  
  /**
   * 提交支付
   */
  async submitPayment() {
    if (!this.agreedToTerms) {
      uni.showToast({
        title: '请先同意服务协议',
        icon: 'none'
      });
      return;
    }
    
    this.paying = true;
    
    try {
      // 创建订单
      const orderResponse = await post('/orders/create', {
        expertId: this.expertId,
        serviceType: this.serviceType,
        originalPrice: this.serviceInfo.price,
        couponId: this.selectedCoupon?.id,
        paymentMethod: this.selectedPaymentMethod
      });
      
      const order: Order = orderResponse.data.order;
      
      // 发起支付
      await this.processPayment(order);
      
    } catch (error) {
      console.error('支付失败:', error);
      uni.showToast({
        title: '支付失败，请重试',
        icon: 'none'
      });
    } finally {
      this.paying = false;
    }
  }
  
  /**
   * 处理支付
   */
  async processPayment(order: Order) {
    try {
      let paymentResult;
      
      switch (this.selectedPaymentMethod) {
        case 'wechat':
          paymentResult = await this.wechatPay(order);
          break;
        case 'alipay':
          paymentResult = await this.alipay(order);
          break;
        case 'balance':
          paymentResult = await this.balancePay(order);
          break;
        default:
          throw new Error('不支持的支付方式');
      }
      
      if (paymentResult.success) {
        // 支付成功
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        // 跳转到咨询页面
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/consult/consult?orderId=${order.id}`
          });
        }, 1500);
      } else {
        throw new Error(paymentResult.message || '支付失败');
      }
      
    } catch (error) {
      console.error('支付处理失败:', error);
      throw error;
    }
  }
  
  /**
   * 微信支付
   */
  async wechatPay(order: Order): Promise<{ success: boolean; message?: string }> {
    try {
      const response = await post('/payment/wechat', {
        orderId: order.id,
        amount: order.finalPrice
      });
      
      const paymentParams = response.data.paymentParams;
      
      // 调用微信支付
      return new Promise((resolve) => {
        // #ifdef MP-WEIXIN
        uni.requestPayment({
          provider: 'wxpay',
          ...paymentParams,
          success: () => {
            resolve({ success: true });
          },
          fail: (error: any) => {
            resolve({ success: false, message: error.errMsg });
          }
        });
        // #endif
        
        // #ifndef MP-WEIXIN
        // H5或其他平台的处理
        resolve({ success: true });
        // #endif
      });
    } catch (error) {
      return { success: false, message: '微信支付失败' };
    }
  }
  
  /**
   * 支付宝支付
   */
  async alipay(order: Order): Promise<{ success: boolean; message?: string }> {
    try {
      const response = await post('/payment/alipay', {
        orderId: order.id,
        amount: order.finalPrice
      });
      
      const paymentParams = response.data.paymentParams;
      
      // 调用支付宝支付
      return new Promise((resolve) => {
        // #ifdef MP-ALIPAY
        uni.requestPayment({
          provider: 'alipay',
          ...paymentParams,
          success: () => {
            resolve({ success: true });
          },
          fail: (error: any) => {
            resolve({ success: false, message: error.errMsg });
          }
        });
        // #endif
        
        // #ifndef MP-ALIPAY
        // H5或其他平台的处理
        resolve({ success: true });
        // #endif
      });
    } catch (error) {
      return { success: false, message: '支付宝支付失败' };
    }
  }
  
  /**
   * 余额支付
   */
  async balancePay(order: Order): Promise<{ success: boolean; message?: string }> {
    try {
      const response = await post('/payment/balance', {
        orderId: order.id,
        amount: order.finalPrice
      });
      
      return { success: response.data.success };
    } catch (error) {
      return { success: false, message: '余额不足' };
    }
  }
  
  /**
   * 格式化日期
   */
  formatDate(dateString: string): string {
    const date = new Date(dateString);
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
  }
  
  /**
   * 获取模拟专家数据
   */
  getMockExpert(): Expert {
    return {
      id: this.expertId,
      name: '张医生',
      avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20pediatrician%20doctor&image_size=square',
      title: '主任医师',
      hospital: '北京儿童医院'
    };
  }
  
  /**
   * 获取模拟优惠券数据
   */
  getMockCoupons(): Coupon[] {
    return [
      {
        id: '1',
        name: '新用户专享',
        discount: 10,
        condition: '满30元可用',
        expireTime: '2024-12-31T23:59:59Z',
        minAmount: 30
      },
      {
        id: '2',
        name: '咨询优惠券',
        discount: 5,
        condition: '无门槛使用',
        expireTime: '2024-06-30T23:59:59Z',
        minAmount: 0
      }
    ];
  }
}
</script>

<style lang="scss" scoped>
.payment-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.order-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .expert-info {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .expert-details {
      flex: 1;
      margin-left: 20rpx;
      
      .expert-name {
        display: block;
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .expert-title {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
  
  .service-info {
    .service-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .service-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .service-value {
        font-size: 28rpx;
        color: #333;
        text-align: right;
        flex: 1;
        margin-left: 20rpx;
      }
      
      .service-price {
        font-size: 30rpx;
        font-weight: 600;
        color: #ff4757;
      }
    }
  }
}

.coupon-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .coupon-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .coupon-info {
      display: flex;
      align-items: center;
      
      .coupon-text {
        margin-left: 10rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
    
    .coupon-discount {
      display: flex;
      align-items: center;
      
      .discount-text {
        font-size: 26rpx;
        color: #ff4757;
        margin-right: 10rpx;
      }
    }
  }
}

.cost-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .cost-list {
    .cost-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15rpx 0;
      
      .cost-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .cost-value {
        font-size: 28rpx;
        color: #333;
      }
      
      &.discount {
        .cost-value {
          color: #ff4757;
        }
      }
      
      &.total {
        border-top: 1rpx solid #f0f0f0;
        padding-top: 20rpx;
        margin-top: 10rpx;
        
        .cost-label {
          font-size: 30rpx;
          font-weight: 600;
          color: #333;
        }
        
        .total-price {
          font-size: 32rpx;
          font-weight: 600;
          color: #ff4757;
        }
      }
    }
  }
}

.payment-method-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .payment-methods {
    .payment-method {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      &.active {
        background-color: #f0f8ff;
        margin: 0 -30rpx;
        padding: 20rpx 30rpx;
        border-radius: 12rpx;
      }
      
      .method-info {
        display: flex;
        align-items: center;
        
        .method-name {
          margin-left: 15rpx;
          font-size: 28rpx;
          color: #333;
        }
      }
    }
  }
}

.agreement-section {
  background-color: white;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .agreement-checkbox {
    display: flex;
    align-items: center;
    
    .agreement-text {
      margin-left: 10rpx;
      font-size: 26rpx;
      color: #666;
      
      .agreement-link {
        color: #007aff;
      }
    }
  }
}

.bottom-payment {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  
  .payment-info {
    flex: 1;
    
    .payment-label {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 5rpx;
    }
    
    .payment-amount {
      font-size: 36rpx;
      font-weight: 600;
      color: #ff4757;
    }
  }
  
  .pay-button {
    width: 200rpx;
    height: 80rpx;
    font-size: 30rpx;
    font-weight: 600;
  }
}

.coupon-popup {
  background-color: white;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .coupon-list {
    flex: 1;
    padding: 20rpx 30rpx;
    
    .coupon-item {
      display: flex;
      align-items: center;
      padding: 25rpx 20rpx;
      margin-bottom: 20rpx;
      background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
      border-radius: 12rpx;
      position: relative;
      
      &.selected {
        background: linear-gradient(135deg, #007aff 0%, #4da6ff 100%);
      }
      
      .coupon-content {
        flex: 1;
        display: flex;
        
        .coupon-amount {
          display: flex;
          align-items: baseline;
          margin-right: 25rpx;
          
          .coupon-symbol {
            font-size: 24rpx;
            color: white;
            margin-right: 2rpx;
          }
          
          .coupon-value {
            font-size: 48rpx;
            font-weight: 600;
            color: white;
          }
        }
        
        .coupon-details {
          flex: 1;
          
          .coupon-name {
            display: block;
            font-size: 30rpx;
            font-weight: 600;
            color: white;
            margin-bottom: 8rpx;
          }
          
          .coupon-condition {
            display: block;
            font-size: 24rpx;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 5rpx;
          }
          
          .coupon-expire {
            font-size: 22rpx;
            color: rgba(255, 255, 255, 0.7);
          }
        }
      }
      
      .coupon-selector {
        margin-left: 20rpx;
      }
    }
    
    .no-coupons {
      text-align: center;
      padding: 80rpx 0;
      
      .no-coupons-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
  
  .popup-footer {
    padding: 20rpx 30rpx 40rpx;
    
    .confirm-button {
      width: 100%;
      height: 80rpx;
      font-size: 30rpx;
      font-weight: 600;
    }
  }
}
</style>